package com.lsh.radardemo;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class GyroRenderer implements GLSurfaceView.Renderer {
    private Cube mCube;
    private Axis mAxis;
    private final float[] mProjectionMatrix = new float[16];
    private final float[] mViewMatrix = new float[16];
    private final float[] mMVPMatrix = new float[16];

    // 欧拉角
    private float mRoll = 0;
    private float mPitch = 0;
    private float mYaw = 0;

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        // 设置背景色为浅灰色
        GLES20.glClearColor(0.95f, 0.95f, 0.95f, 1.0f);
        // 启用深度测试
        GLES20.glEnable(GLES20.GL_DEPTH_TEST);

        // 创建半透明立方体
        mCube = new Cube(0.7f); // 设置透明度为0.7
        // 创建坐标轴辅助线
        mAxis = new Axis(1.5f); // 设置轴长度为1.5倍立方体大小
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
        float ratio = (float) width / height;
        // 调整视锥体参数以获得更好的视角
        Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 2, 10);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        // 清除颜色和深度缓冲
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

        // 设置相机位置
        Matrix.setLookAtM(mViewMatrix, 0,
                0, 0, -4,  // 相机位置
                0, 0, 0,   // 观察点
                0, 1, 0);  // 上向量

        // 计算模型矩阵
        float[] modelMatrix = new float[16];
        Matrix.setIdentityM(modelMatrix, 0);

        // 应用旋转 - 使用Yaw-Pitch-Roll顺序
        Matrix.rotateM(modelMatrix, 0, mYaw, 0, 0, 1);  // 偏航 (Z轴)
        Matrix.rotateM(modelMatrix, 0, mPitch, 1, 0, 0); // 俯仰 (X轴)
        Matrix.rotateM(modelMatrix, 0, mRoll, 0, 1, 0);  // 横滚 (Y轴)

        // 计算MVP矩阵
        Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, modelMatrix, 0);
        Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

        // 先绘制坐标轴(会穿过立方体中心)
        mAxis.draw(mMVPMatrix);

        // 再绘制立方体
        mCube.draw(mMVPMatrix);
    }

    public void updateOrientation(float roll, float pitch, float yaw) {
        this.mRoll = roll;
        this.mPitch = pitch;
        this.mYaw = yaw;
    }
}